package com.lepu.app.usercenter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import lib.share.login.LoginLib;
import lib.share.login.OnLoginListener;
import lib.share.login.UserInfo;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.Observer;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UtilityBase;
import com.eyzhs.app.R;
import com.lepu.app.usercenter.bean.BeanThirdAccount;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

public class UserOtherLoginActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, AsyncRequest, OnLoginListener,Observer {

	private static final String REQUEST_GET_DATA = "request_get_data";
	private static final String REQUEST_BOND_CLIENT = "request_bond_client";
	
	private int mIsBindMobile = 0;
	private String mMobilePhone = "";
	private ArrayList<BeanThirdAccount> mDataList = null;
	private int mCurrentLoginType = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.usercenter_otherlogin_activity);

		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		
		ObserverManager.getInstance().removeObserver(ObserverConst.NOTIFY_MY_BOND_PHONE_CHANGE);
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("第三方账号");
		topbar.setonTopbarNewLeftLayoutListener(this);

		ObserverManager.getInstance().addObserver(ObserverConst.NOTIFY_MY_BOND_PHONE_CHANGE, this);
		requestData();
	}
	
	private void initData(){
		
		updateBondPhoneUi();
		
		if(mDataList != null && mDataList.size() > 0){
			for(BeanThirdAccount item : mDataList){
				updateBondUI(UtilityBase.parseInt(item.TATID));
			}
		}
	}

	private void requestData() {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			
		} catch (Exception e) {
		}
		map.put("ht", params);

		showProgressDialog();
		ApiClient.http_post_main(Setting.getTirdpartyAccountList(), map, null, this,
				REQUEST_GET_DATA, true,false,true);
	}

	private void requestBondClient(String ThirdpartyAccount, String TAAccessToken, String TAAccessTokenExpireTime) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			
			params.put("ThirdpartyAccount", ThirdpartyAccount);
            params.put("TATID", mCurrentLoginType);
            params.put("TAAccessToken", TAAccessToken);
            params.put("TAAccessTokenExpireTime", TAAccessTokenExpireTime);
            //params.put("NickName", NickName);//这个参数不传也可以，
			
		} catch (Exception e) {
		}
		map.put("ht", params);

		showProgressDialog(false);
		ApiClient.http_post_main(Setting.getBindTirdpartyAccount(), map, null, this,
				REQUEST_BOND_CLIENT, true);
	}

	public void layoutClick(View view) {
		int rid = view.getId();
		switch (rid) {
		case R.id.bondPhoneLayout:
			Intent intent = new Intent(this, UserBondActivity.class);
			startActivity(intent, true);
			break;
		case R.id.bondWXLayout:
		case R.id.bondQQLayout:
		case R.id.bondWeiBoLayout:

			LoginLib loginLib = LoginLib
					.getInstance(UserOtherLoginActivity.this);
			loginLib.setOnLoginListener(UserOtherLoginActivity.this);

			if (rid == R.id.bondWXLayout) {
				mCurrentLoginType = LoginLib.TYPE_LOGIN_WX;
				loginLib.loginWeixin();
			} else if (rid == R.id.bondQQLayout) {
				mCurrentLoginType = LoginLib.TYPE_LOGIN_QQ;
				loginLib.loginQQ();
			} else if (rid == R.id.bondWeiBoLayout) {
				mCurrentLoginType = LoginLib.TYPE_LOGIN_WEIBO;
				loginLib.loginSinaWeibo();
			}
			break;

		default:
			break;
		}
	}
	
	private void updateBondUI(int type)
	{
		if(type == LoginLib.TYPE_LOGIN_WX)
		{
			RelativeLayout bondWXLayout = (RelativeLayout) findViewById(R.id.bondWXLayout);
			TextView bondWXStateTextView = (TextView) findViewById(R.id.bondWXStateTextView);
			ImageView bondWXArrowImageView = (ImageView) findViewById(R.id.bondWXArrowImageView);
			
			bondWXLayout.setEnabled(false);
			bondWXStateTextView.setText("已绑定");
			bondWXArrowImageView.setVisibility(View.GONE);
			
		}else if(type == LoginLib.TYPE_LOGIN_QQ)
		{
			RelativeLayout bondQQLayout = (RelativeLayout) findViewById(R.id.bondQQLayout);
			TextView bondQQStateTextView = (TextView) findViewById(R.id.bondQQStateTextView);
			ImageView bondQQArrowImageView = (ImageView) findViewById(R.id.bondQQArrowImageView);
			
			bondQQLayout.setEnabled(false);
			bondQQStateTextView.setText("已绑定");
			bondQQArrowImageView.setVisibility(View.GONE);
		}else if(type == LoginLib.TYPE_LOGIN_WEIBO)
		{
			RelativeLayout bondWeiBoLayout = (RelativeLayout) findViewById(R.id.bondWeiBoLayout);
			TextView bondWeiBoStateTextView = (TextView) findViewById(R.id.bondWeiBoStateTextView);
			ImageView bondWeiBoArrowImageView = (ImageView) findViewById(R.id.bondWeiBoArrowImageView);
			
			bondWeiBoLayout.setEnabled(false);
			bondWeiBoStateTextView.setText("已绑定");
			bondWeiBoArrowImageView.setVisibility(View.GONE);
		}else{
			//
		}
	}
	
	private void updateBondPhoneUi()
	{
		//phone
		RelativeLayout bondPhoneLayout = (RelativeLayout) findViewById(R.id.bondPhoneLayout);
		TextView bondPhoneStateTextView = (TextView) findViewById(R.id.bondPhoneStateTextView);
		ImageView bondPhoneArrowImageView = (ImageView) findViewById(R.id.bondPhoneArrowImageView);
		
		if(mIsBindMobile == 1)
		{
			bondPhoneLayout.setEnabled(false);
			bondPhoneStateTextView.setText("已绑定");
			bondPhoneArrowImageView.setVisibility(View.GONE);
			
			TextView bondPhoneTextView = (TextView) findViewById(R.id.bondPhoneTextView);
			bondPhoneTextView.setText(mMobilePhone);
		}
		
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_GET_DATA)) {
			hideProgressDialog();
			String result = (String) data;
			JSONObject dataObject = null;
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				dataObject = (JSONObject) obj1.get("DetailInfo");
				
				mIsBindMobile = dataObject.optInt("IsBindMobile");
				mMobilePhone = dataObject.optString("MobilePhone");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			mDataList = BeanThirdAccount.parseJsonData(result);
			initData();
		} else if (object.equals(REQUEST_BOND_CLIENT)) {
			hideProgressDialog();
			updateBondUI(mCurrentLoginType);
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String data) {
		if (object.equals(REQUEST_GET_DATA)) {
			hideProgressDialog();
		} else if (object.equals(REQUEST_BOND_CLIENT)) {
			hideProgressDialog();
		}
	}

	@Override
	public void onSignUp(UserInfo info) {
		if (info != null) {
			LogUtilBase.LogD(null, info.toString());
			requestBondClient(info.userId,info.userToken,String.valueOf(info.userExpiresTime));
		}
	}

	@Override
	public void notify(String name, Object sender, Object data) {
		if(name.equals(ObserverConst.NOTIFY_MY_BOND_PHONE_CHANGE))
		{
			mIsBindMobile = 1;
			mMobilePhone = (String) data;

			updateBondPhoneUi();
		}
	}

}
